<style lang="less">
</style>
<template>
  <div>
    <Form :model="seachForm" inline :label-width="80" v-show="!isEditing">
      <FormItem prop="name" :label="$t('name')">
        <Input v-model="seachForm.name" placeholder="请输入课程名"></Input>
      </FormItem>
      <FormItem>
        <Button icon="ios-search" @click="seacherSubmit('seacherForm')">查询</Button>
      </FormItem>
    </Form>

    <ButtonGroup v-show="!isEditing">
      <Button icon="ios-add" @click="btnAddClick">新增</Button>
      <Button icon="ios-create" @click="btnEditClick" :disabled="!currentRow">修改</Button>
      <Button icon="ios-trash" @click="btnDelClick" :disabled="!currentRow">删除</Button>
    </ButtonGroup>

    <Table v-show="!isEditing" border highlight-row ref="currentRowTable" @on-current-change="tableCurrentChange"
           :columns="columns" :data="datas"></Table>
    <Page :total="pageInfo.totalRows" @on-change="pageNumberChange" v-show="!isEditing"/>
    <Form v-if="isEditing" :model="dataForm" :label-width="80" :rules="validateRules">
      <FormItem prop="content" :label="$t('q_content')">
        <Input v-model="dataForm.content" placeholder="请输入题干" :rows="4" type="textarea"></Input>
      </FormItem>
      <FormItem prop="type" :label="$t('type')">
        <i-select v-model="dataForm.type">
          <i-option v-for="item in typeList" :value="item.value" :key="item.value">{{ item.label }}</i-option>
        </i-select>
      </FormItem>
      <FormItem prop="answer" :label="$t('answer')">
        <AnswerRadio v-if="dataForm.type===1" :answers.sync="dataForm.answers" :rightAnswer.sync="dataForm.rightAnswer"/>
        <AnswerCheckBox v-else-if="dataForm.type===2" :answers.sync="dataForm.answers" :rightAnswer.sync="dataForm.rightAnswer"/>
        <AnswerJudge v-else-if="dataForm.type===3" :rightAnswer.sync="dataForm.rightAnswer"/>
        <AnswerCompute v-else-if="dataForm.type===4" :rightAnswer.sync="dataForm.rightAnswer"/>
      </FormItem>
      <FormItem prop="category" :label="$t('category')">
        <Cascader :data="categories" v-model="dataForm.category"></Cascader>
      </FormItem>
      <FormItem prop="status" :label="$t('status')">
        <i-select v-model="dataForm.status">
          <i-option v-for="item in statusList" :value="item.value" :key="item.value">{{ item.label }}</i-option>
        </i-select>
      </FormItem>
      <FormItem prop="tag" :label="$t('tag')">
        <Input v-model="dataForm.tag" type="text"/>
      </FormItem>
      <FormItem>
        <Button type="primary" @click="btnSaveClick">保存</Button>
        <Button type="error" style="margin-left: 8px" @click="btnCancelClick">取消</Button>
      </FormItem>
    </Form>
  </div>
</template>
<script>
  import {getQuestionList, getQuestion, addQuestion, updateQuestion, deleteQuestion} from '@/api/question'
  import AnswerRadio from '../../../components/answer-radio/index';
  import AnswerCheckBox from '../../../components/answer-checkbox/index';
  import AnswerJudge from '../../../components/answer-judge/index';
  import AnswerCompute from '../../../components/answer-compute/index';

  export default {
    name: 'QBank',
    components: {AnswerRadio, AnswerCheckBox, AnswerJudge, AnswerCompute},
    data() {
      return {
        answers: {},
        rightAnswer: '',
        categories: [
          {
            value: '1',
            label: '操作系统',

          },
          {
            value: '2',
            label: '数据库',

          }],
        validateRules: {
          content: [{type: "string", required: true, message: '必填项', trigger: 'blur'}],
          category: [{required: true, message: '必填项'}],
          status: [{type: "number", required: true, message: '必填项'}],
          type: [{type: "number", required: true, message: '必填项'}],
          tag: [{type: "string", required: true, message: '必填项'}],
          // answer: [{type: "string", required: true, message: '必填项'}],
        },
        statusList: [
          {label: '正常', value: 1},
          {label: '禁用', value: 2},
          {label: '待审核', value: 3},
        ],
        typeList: [
          {label: '单选', value: 1},
          {label: '多选', value: 2},
          {label: '判断', value: 3},
          {label: '简答', value: 4},
        ],
        currentRow: null,
        isEditing: false,
        seachForm: {
          name: '',
          address: ''
        },
        pageInfo: {
          pageNumber: 1,
          pageSize: 10,
          totalRows: 0
        },
        dataForm: {
          status: 1,
          type: 1
        },
        types: [
          '单选',
          '多选',
          '判断',
          '简答',
        ],
        columns: [
          {
            type: 'index',
            width: 60,
            align: 'center',
          },
          {
            width: 60,
            align: 'center',
            title: 'Id',
            key: 'id'
          },
          {
            title: this.$t('q_content'),
            key: 'content',
          },

          {
            title: this.$t('q_type'),
            key: 'type',
            render(create, record) {
              const types = [
                '单选',
                '多选',
                '判断',
                '简答',
              ];
              return create('span', types[record.row.type - 1])
            }
          },

          {
            title: this.$t('right_count'),
            key: 'right'
          },
          {
            title: this.$t('wrong_count'),
            key: 'wrong'
          },
          {
            title: this.$t('username'),
            key: 'name'
          },
          {
            title: this.$t('tag'),
            key: 'tag',
            render(create, record) {
              return create('div', {}, record.row.tag.split(',').map((item => {
                  if (item) {
                    return create('Tag',
                      {
                        props: {
                          type: 'border',
                          color: 'primary'
                        },
                        domProps: {
                          innerHTML: item,
                        },
                      })
                  }
                }
              )))
            }
          },
          {
            title: this.$t('status'),
            key: 'status',
            align: 'center',
            render: (create, record) => {
              const status = record.row.status;
              const statusMap = {
                'success': '正常',
                'warning': '待审核',
                'error': '禁用'
              };
              let clazz = 'success';
              if (status === 2) { //禁用
                clazz = 'error';
              } else if (status === 3) { // 待审核
                clazz = 'warning';
              }
              return create('Tag', {
                props: {
                  type: clazz
                },
                domProps: {
                  innerHTML: statusMap[clazz],
                },
              });
            }
          },
        ],
        datas: [],
        timeRange: ''
      }
    },
    mounted() {
      this.queryList();
    },
    methods: {
      seacherSubmit: function () {
        this.pageInfo.pageNumber = 1;
        this.queryList();
      },
      queryList: function () {
        var queryParams = {
          name: this.seachForm.name,
          pageNumber: this.pageInfo.pageNumber,
          pageSize: this.pageInfo.pageSize
        };
        getQuestionList(queryParams).then(res => {
          this.datas = res.data.rows;
          this.datas.map(item => {
            let content = JSON.parse(item.content);
            item.content = content.content;
            item.rightAnswer = content.rightAnswer;
            item.answers = content.answers;
            item.category = JSON.parse(item.cate_id);
            delete item.cate_id;
          });
          this.pageInfo.totalRows = parseInt(res.data.total);
        });
      },
      pageNumberChange: function (pagenum) {
        this.pageInfo.pageNumber = pagenum;
        this.queryList();
      },

      tableCurrentChange: function (currentRow, oldCurrentRow) {
        this.currentRow = currentRow;
      },
      btnAddClick: function () {
        this.dataForm = {status: 1, type: 1};
        this.isEditing = true;
      },
      btnEditClick: function () {
        this.dataForm = this.currentRow;
        this.isEditing = true;
      },
      btnDelClick: function () {
        this.$Modal.confirm({
          title: '删除',
          content: '确定要删除选中的信息吗?',
          onOk: () => {
            this.delData();
          }
        });
      },
      btnSaveClick: function () {
        let dataForm = {
          type: this.dataForm.type,
          tag: this.dataForm.tag,
          status: this.dataForm.status
        };
        if (this.dataForm.id) {
          dataForm.id = this.dataForm.id;
        }
        dataForm.cate_id = JSON.stringify(this.dataForm.category);
        let content = {
          content: this.dataForm.content,
          answers: this.dataForm.answers
        };
        if (this.type !== 2 && this.dataForm.rightAnswer) {
          content.rightAnswer = this.dataForm.rightAnswer;
        }
        dataForm.content = JSON.stringify(content);
        if (dataForm.id) {
          updateQuestion(dataForm.id, dataForm).then(res => {
            if (res.data && res.data.affectedRows > 0) {
              this.$Message.success('保存成功!');
              this.queryList();
              this.isEditing = false;
            } else {
              this.$Message.error(res.error);
            }
          });
        } else {
          addQuestion(dataForm).then(res => {
            if (res.data && res.data.affectedRows > 0) {
              this.$Message.success('保存成功!');
              this.queryList();
              this.isEditing = false;
            } else {
              this.$Message.error(res.error);
            }
          });
        }
      },
      btnCancelClick: function () {
        this.isEditing = false;
      },
      delData: function () {
        deleteQuestion(this.currentRow.id).then(res => {
          console.log(res);
          if (res.data && res.data.affectedRows > 0) {
            this.$Message.success('删除成功!');
            this.queryList();
          } else {
            this.$Message.error('删除失败!');
          }
        });
      },
    },
  }

</script>
